/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx.wxs.utils;

import java.security.MessageDigest;
import java.util.UUID;

/**
 * <p>Project: wxshop - Md5SaltUtil
 * <p>Powered by webrx On 2021-04-18 09:37:06
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 15
 */
public class Md5SaltUtil {
    /**
     * 返回加密后的密文和salt
     *
     * @param account   zs 123 ls 123
     * @param passwd
     * @return String[]
     */
    public static String[] encrytionPassword(String account, String passwd) {
        StringBuilder su = new StringBuilder();
        su.append(account);
        su.append(passwd);
        String salt = UUID.randomUUID().toString().toLowerCase().replaceAll("-", "");
        su.append(salt);  //accountpasswordsalt
        String m5 = md5(su.toString());
        String sh = sha(su.toString());
        //32 md5
        String ss = m5.substring(0, 6) + sh.substring(0, 6) + m5.substring(10, 15) + sh.substring(10, 15) + m5.substring(27) + sh.substring(35);
        return new String[]{ss, salt};
    }

    public static boolean verfiyPassword(String account, String passwd, String salt, String password) {
        boolean f = false;
        StringBuilder su = new StringBuilder();
        su.append(account);
        su.append(passwd);
        su.append(salt);
        String m5 = md5(su.toString());
        String sh = sha(su.toString());
        String ss = m5.substring(0, 6) + sh.substring(0, 6) + m5.substring(10, 15) + sh.substring(10, 15) + m5.substring(27) + sh.substring(35);
        if (ss.equals(password)) f = true;
        return f;
    }

    /**
     * 返回40位16进制密文
     *
     * @param str
     * @return
     */
    public static String sha(String str) {
        StringBuilder s = new StringBuilder(40);
        try {
            MessageDigest md = MessageDigest.getInstance("sha");
            md.update(str.getBytes());
            for (byte b : md.digest()) {
                String s2 = String.format("%x", b);
                s.append(s2.length() == 2 ? s2 : "0" + s2);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s.toString();
    }

    /**
     * 返回32位16进制密文
     *
     * @param str
     * @return
     */
    public static String md5(String str) {
        StringBuilder s = new StringBuilder(32);
        try {
            MessageDigest md = MessageDigest.getInstance("md5");
            md.update(str.getBytes());
            for (byte b : md.digest()) {
                String s2 = String.format("%x", b);
                s.append(s2.length() == 2 ? s2 : "0" + s2);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s.toString();
    }
}